﻿using Mapster;
using MediatR;
using Service.Auth.Api.Application.Query;
using Service.Auth.Domain.AggregatesModel;
using Service.Core.Repository;
using Service.Core.Repository.Attribute;
using Service.Auth.Api.Application.Command;

namespace Service.Auth.Api.Application.Handler.CommandHandler;

// Regular CommandHandler

/// <summary>
/// 
/// </summary>
/// <param name="repository"></param>
/// <param name="systemQueryService"></param>
public class UserSystemRoleCommandHandler(IRepository<UserSystemRole> repository, SystemQueryService systemQueryService) :
        IRequestHandler<CreateUserSystemRolesCommand, bool>,
    IRequestHandler<UpdateUserSystemRoleNumByRoleIdCommand, bool>
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task<bool> Handle(CreateUserSystemRolesCommand request, CancellationToken cancellationToken)
    {

        var createUserSystemRolesDto = request.CreateUserSystemRolesDto;

        var userSystemRole = await repository.GetListAsync(s => s.UserId == createUserSystemRolesDto.UserId,
            cancellationToken: cancellationToken);
        if (userSystemRole.Any())
            await repository.DeleteRangeAsync(userSystemRole, cancellationToken);

        var systemIds = createUserSystemRolesDto.UserSystemRoles.Select(s => s.SystemId).ToList();

        var systems = await systemQueryService.QuerySystemsByIds(systemIds);

        createUserSystemRolesDto.UserSystemRoles.ForEach(s =>
        {
            var system = systems.FirstOrDefault(c => c.Id.Equals(s.SystemId));
            s.SystemName = system?.SystemName ?? string.Empty;
        });
        var userSystemRoles = createUserSystemRolesDto.UserSystemRoles.Adapt<List<UserSystemRole>>();
        return await repository.InsertRangeAsync(userSystemRoles, cancellationToken);
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task<bool> Handle(UpdateUserSystemRoleNumByRoleIdCommand request, CancellationToken cancellationToken)
    {
        var userSystemRoleNumDto = request.UserSystemRoleNumDto;

        var userSystemRoles = await repository.GetListAsync(s => s.RoleId.Equals(userSystemRoleNumDto.RoleId), cancellationToken: cancellationToken);
        userSystemRoles.ForEach(s =>
        {
            s.SerRoleNum(userSystemRoleNumDto.RoleNum);
        });
        return await repository.UpdateRangeAsync(userSystemRoles, cancellationToken);
    }
}

